from django.db import transaction
from rest_framework import serializers

from goods_app.models import SKU


class SkuSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(read_only=True)
    update_time = serializers.DateTimeField(read_only=True)

    class Meta:
        exclude = ['default_image']
        model = SKU

    def create(self, validated_data):
        with transaction.atomic():
            sid = transaction.savepoint()  # 保存点
            try:
                sku = SKU.objects.create(**validated_data)
            except:
                transaction.savepoint_rollback(sid)  # 出错->回滚
                return serializers.ValidationError("数据库保存出错")
            else:
                transaction.savepoint_commit(sid)  # 成功->保存
        return sku

    def update(self, instance, validated_data):
        with transaction.atomic():
            sid = transaction.savepoint()
            try:
                instance.name = validated_data.get('name', instance.name)
                instance.caption = validated_data.get('caption',
                                                      instance.caption)
                instance.price = validated_data.get('price', instance.price)
                instance.cost_price = validated_data.get('cost_price',
                                                         instance.cost_price)
                instance.market_price = validated_data.get('market_price',
                                                           instance.market_price)
                instance.save()
            except:
                transaction.savepoint_rollback(sid)
                return serializers.ValidationError("数据库保存出错")
            else:
                transaction.savepoint_commit(sid)
        return instance
